package com.bw.mine.ui

import android.view.View
import androidx.lifecycle.ViewModelProviders
import com.bw.mine.databinding.ActivityRegisterBinding
import com.bw.mine.intent.RegisterIntent
import com.bw.mine.model.service.RegisterModel
import com.bw.mine.state.RegisterState
import com.bw.mvicore.ui.BaseMVIActivity

class RegisterActivity : BaseMVIActivity() {
    private lateinit var binding:ActivityRegisterBinding
    private lateinit var model:RegisterModel
    override fun generateModel() {
        model=ViewModelProviders.of(this).get(RegisterModel::class.java)
    }

    override fun releaseRes() {

    }

    override fun generateContentView(): View {
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initData() {

    }

    override fun initEvent() {
        binding.btnMineRegReg.setOnClickListener {
            val username = binding.etMineRegUsername.text.toString().trim()
            val pwd = binding.etMineRegPwd.text.toString().trim()
            val pwdAgain = binding.etMineRegPwdAgain.text.toString().trim()
            if (username.isBlank()){
                showMsg("请输入用户名")
                return@setOnClickListener
            }
            if (pwd.isBlank()){
                showMsg("请输入密码")
                return@setOnClickListener
            }
            if (pwdAgain.isBlank()){
                showMsg("请再次输入密码")
                return@setOnClickListener
            }
            if (pwd!=pwdAgain){
                showMsg("两次密码输入不一致，请重新输入")
                binding.etMineRegPwd.text.clear()
                binding.etMineRegPwdAgain.text.clear()
                return@setOnClickListener
            }

            generateLifeCycleLaunch {
                model.intents.send(RegisterIntent.FinalRegisterIntent(username,pwd))
            }
        }
    }

    override fun handleState() {
        generateLifeCycleLaunch {
            model.state.collect{
                when(it){
                    is RegisterState.RegisterDefaultState->{}
                    is RegisterState.RegisterSuccessState->{
                        closeThiz()
                    }
                    is RegisterState.RegisterFailedState->{
                        showMsg("注册失败，errinfo:${it.throwable.message}")
                    }
                }
            }
        }
    }
}